import 'dart:io';
import 'package:inmotion_pro/l10n/local.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:inmotion_pro/service/permission_service.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';

mixin UserBasicInformationMixin {
  // 点击头像
  mixinClickAvatar({Function(String)? callback}) {
    LxBottomSheet.show(
      Get.context!,
      dataArr: [
        local.take_photo,
        local.select_from_album,
      ],
      selectedCallback: (selectIndex, selectedString) {
        debugPrint('选中: $selectIndex, $selectedString');
        if (selectIndex == 0) {
          _takePhoto(callback: callback);
        } else if (selectIndex == 1) {
          _selectFromAlbum(callback: callback);
        }
      },
    );
  }

  // 拍照
  _takePhoto({Function(String)? callback}) {
    PermissionService.to.requestPhotoPermission((success) async {
      if (success) {
        try {
          final XFile? photo =
              await ImagePicker().pickImage(source: ImageSource.camera);
          if (photo != null) {
            debugPrint('拍照成功: ${photo.path}, type: ${photo.mimeType}');
            // 处理照片
            if (callback != null) {
              // 调用回调函数
              callback(photo.path);
            }
          }
        } catch (e) {
          debugPrint('拍照错误: $e');
          Loading.showToast('拍照错误: $e');
        }
      } else {
        debugPrint('用户取消了选择');
      }
    });
  }

  // 从相册选择
  _selectFromAlbum({Function(String)? callback}) {
    PermissionService.to.requestCameraPermission((success) async {
      if (success) {
        try {
          final XFile? pickedFile =
              await ImagePicker().pickImage(source: ImageSource.gallery);

          if (pickedFile != null) {
            // 获取图片文件
            final imageFile = File(pickedFile.path);
            debugPrint("图片路径: ${imageFile.path}");
            if (callback != null) {
              // 调用回调函数
              callback(imageFile.path);
            }
          } else {
            debugPrint("用户取消了选择");
          }
        } catch (e) {
          debugPrint('拍照错误: $e');
          Loading.showToast('拍照错误: $e');
        }
      } else {
        debugPrint('用户取消了选择');
      }
    });
  }
}
